package org.kent.w.base.common.executor;

import java.util.Collection;
import java.util.Enumeration;
import java.util.concurrent.*;

/**
 * 线程池
 *
 * @author wu.jigang@geely.com
 * @version 1.0
 * @Date :Created by 2020/3/5.
 */
public class ThreadPools {

    private static ConcurrentHashMap<String, Collection> POOL_MAP = new ConcurrentHashMap<>();

    /****
     * 支持扩展的线程池配置
     *
     * @param name       线程池名称
     * @param cores      核心线程数
     * @param maxThreads 最大线程数
     * @param queues     队列最大长度
     * @param alive      线程存活时间
     * @return
     */
    public static ExecutorService getExecutor(String name, int cores, int maxThreads, int queues, int alive) {


        BlockingQueue<Runnable> workQueue = null;

        if (queues <= 0) {
            workQueue = new SynchronousQueue<Runnable>();
        } else {
            workQueue = new LinkedBlockingQueue<Runnable>(queues);
        }
        POOL_MAP.put(name, workQueue);

        return new ThreadPoolExecutor(cores, maxThreads, alive, TimeUnit.MILLISECONDS, workQueue,
                new NamedThreadFactory(name, true), new AbortPolicyWithReport(name));
    }

    /****
     * 默认线程池
     *
     * @param name 线程池名称
     * @return
     */
    public static ExecutorService getDefaultExecutor(String name) {

        return getExecutor(name, 10, 20, 20000, 60 * 1000);
    }

    /***
     * 获取队列长度;
     *
     * @param name
     * @return
     */
    public static int geQueueSize(String name) {
        Collection collection = POOL_MAP.get(name);
        return collection.size();
    }

    /***
     * 获取线程池的列表名称
     *
     * @return
     */
    public static Enumeration<String> getNames() {
        return POOL_MAP.keys();
    }

    /***
     * 线程池优雅关停
     *
     * @param executor 线程池
     * @param timeout  超时时间(豪秒)
     */
    public static void gracefulShutdown(Executor executor, int timeout) {

        if (executor == null) return;

        ExecutorUtil.gracefulShutdown(executor, timeout);
    }
}
